package dao;

import entity.Artist;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.StringTokenizer;
import javax.persistence.*;

/**
 *
 * @author Javier
 */
public class ArtistDao {
    private EntityManagerFactory emf = null;
    private EntityManager em = null;
    private EntityTransaction et = null;
    
    public boolean persistArtist(Artist artist){    
        boolean result=false;
        try{
        emf = Persistence.createEntityManagerFactory("GRLUPUPU");
        em = emf.createEntityManager();
        et = em.getTransaction();
        et.begin();
        
        artist = em.merge(artist);
        em.flush();
        em.persist(artist);
        
        et.commit(); 
        result=true;
        }catch(Exception e){
            if (em != null && et != null){
                et.rollback();
            }
        }finally{
            if (em != null){
                em.clear();
                em.close();
            }
            return result;
        }
    }
       
    public List<Artist> findAllArtistByNameAndLastname (String artistName, String artistLastname){
        List<Artist> artists = null;
        try{
        emf = Persistence.createEntityManagerFactory("GRLUPUPU");
        em = emf.createEntityManager();
        et = em.getTransaction();
        et.begin();        
        Query q = em.createQuery("SELECT a FROM Artist a WHERE a.art_Name LIKE :artName OR a.art_Lastname LIKE :artLastname");
        q.setParameter("artName", artistName);
        q.setParameter("artLastname", artistLastname);
        artists = q.getResultList();        
        et.commit(); 
        }catch(Exception e){
            if (em != null && et != null){
                et.rollback();
            }
        }finally{
            if (em != null){
                em.clear();
                em.close();
            }
            return artists;
        }
    }
    
    
    public List<Artist> findAllActorsByName(String wordsToLookFor){
        //Returned value
        List<Artist> movies = new ArrayList();
        // Set which contains the movie's id only once
        HashSet<Integer> actorsId = new HashSet();
        
        //Divide the string into its tokens.
        //String wordsToLookFor = "palabras para la busqueda de peliculas";
        StringTokenizer tokens=new StringTokenizer(wordsToLookFor, " ");
        ArrayList<String> words = new ArrayList();
        int j = 0;
        while (tokens.hasMoreTokens()){
            String next=tokens.nextToken();
            words.add(next);
            //System.out.println(words.get(j).toString());
            j++;
        }
        
        for( int i = 0; i < words.size(); i++){
            // List of movies in each iteration.
            List<Artist> a;
        
            try{
                    emf = Persistence.createEntityManagerFactory("GRLUPUPU");
                    em = emf.createEntityManager();
                    et = em.getTransaction();
                    et.begin();

                    String qlString = "SELECT a FROM Artist AS a WHERE a.artName LIKE :code OR a.artLastname LIKE :code"; 
                    Query q = em.createQuery(qlString, Artist.class);
                    q.setParameter("code", "%"+words.get(i).toString()+"%");
                    a = q.getResultList();
                    //Adding the Id's only once
                    for ( int k = 0; k < a.size(); k++){
                        actorsId.add(new Integer (a.get(k).getIdArtist()));
                    }

                    et.commit();    
                }catch(Exception e){
                    if (em != null && et != null){
                        et.rollback();
                    }
                }finally{
                    if (em != null){
                        em.clear();
                        em.close();
                     }   
                }
                Object[] result = actorsId.toArray();
                for (int l = 0; l < actorsId.size(); l++){
                    movies.add((Artist)findArtistById((Integer)result[l]));
                }
        }
        return movies;
    }
    
    public Artist findArtistById(Integer id){
        Artist artist = null;
        try{
            emf = Persistence.createEntityManagerFactory("GRLUPUPU");
            em = emf.createEntityManager();
            et = em.getTransaction();
            et.begin();

            Query q = em.createNamedQuery("Actor.findByIdActor", Artist.class);
            q.setParameter("idArtist", id);
            artist = (Artist) q.getSingleResult();
            et.commit();

        }catch(Exception e){
            if (em != null && et != null){
                et.rollback();
            }
        }finally{
            if (em != null){
                em.clear();
                em.close();
            }

        }     
        return artist;
    }
    
    
    public boolean deleteArtist(Artist artist) {
        boolean result = false;
        try {
            emf = Persistence.createEntityManagerFactory("GRLUPUPU");
            em = emf.createEntityManager();
            et = em.getTransaction();
            et.begin();        
            em.remove(artist);
            em.getTransaction().commit();
            result = true;
        } catch (Exception e) {
            if (em != null && et != null){
                et.rollback();
            }
        } finally {
            if (em != null){
                em.clear();
                em.close();
            }
            return result;
        }
    }
    
}